<template>
  <div>
    <div class="oa-header">
      <div class="oa-header-logo image-logo"></div>
      <div class="oa-header-id">{{user && user.realname}}</div>
      <div class="oa-header-nav">
        <ul class="clearfix">
          <li v-for="(item,index) in menus"
              v-if="!item.index"
              :key="index"
              @mouseover="item.show = true"
              @mouseout="item.show = false">
            <span>
              {{item.name}}
              <i class="el-icon-arrow-down"
                 v-if="item.isParent"></i>
            </span>
            <div class="oa-header-nav-select"
                 v-show="item.show === true"
                 v-if="item.menus && item.menus.length > 0">
              <h3 v-if="item.directlyMenus.length > 0">{{item.name}}</h3>
              <ul class="clearfix"
                  v-if="item.directlyMenus.length > 0">
                <li v-for="(item2, index2) in item.directlyMenus"
                    :key="index2"
                    @click="openFromMenu(item2), item.show = false">
                  <el-badge :value="item2.tag | data-config('RESOURCETAG')"
                            v-if="item2.tag">
                    {{item2.name}}
                  </el-badge>
                  <span v-else>{{item2.name}}</span>
                </li>
              </ul>
              <div v-for="(item2, index2) in item.indirectMenus"
                   :key="index2"
                   v-if="item.indirectMenus.length > 0">
                <h3>
                  {{item2.name}}
                </h3>
                <el-badge :value="item2.tag | data-config('RESOURCETAG')"
                          v-if="item2.tag"></el-badge>
                <ul class="clearfix"
                    v-if="item2.menus && item2.menus.length > 0">
                  <li v-for="(item3, index3) in item2.menus"
                      :key="index3"
                      @click="openFromMenu(item3)">
                    <el-badge :value="item3.tag | data-config('RESOURCETAG')"
                              v-if="item3.tag">
                      {{item3.name}}
                    </el-badge>
                    <span v-else>{{item3.name}}</span>
                  </li>
                </ul>
              </div>
            </div>
          </li>
        </ul>
      </div>
      <div class="oa-header-msg">
        <ul class="clearfix">
          <li class="oa-header-ms"
              @mouseover="msgDownList = true"
              @mouseout="msgDownList = false"
              @click="viewAllMyMsg">
            <span>
              <el-badge is-dot
                        :value="messagenum"
                        :hidden="messagenum === 0"
                        class="ms-badge-item">
                <i class="el-icon-bell"></i>
                消息中心
              </el-badge>
            </span>
            <div class="oa-header-ms-box"
                 v-show="msgDownList">
              <ul>
                <li v-for="(obj, index) in messages"
                    @click="jumptourl(obj)"
                    :key="index">
                  {{obj.msg}}
                </li>
                <li @click="viewAllMyMsg"
                    v-if="messagenum > 0">
                  <i class="el-icon-view"></i>
                  查看全部 ({{messagenum}})
                </li>
                <li v-else>
                  暂无新消息
                </li>
              </ul>
            </div>
          </li>
          <li class="oa-header-user"
              @mouseover="userCenter = true"
              @mouseout="userCenter = false">
            <span>
              <i class="el-icon-menu"></i>{{user && user.realname}}</span>
            <div class="oa-header-user-box"
                 v-show="userCenter">
              <ul>
                <li>
                  <i class="el-icon-setting"></i>个人中心</li>
                <li @click="editInfo">
                  <i class="el-icon-edit"></i>修改密码</li>
                <li @click="logout">
                  <i class="el-icon-back"></i>退出登录</li>
              </ul>
            </div>
          </li>
        </ul>
      </div>
    </div>
    <div class="oa-router">
      <div class="oa-router-btn">
        <div @click="refresh">
          <i class="el-icon-refresh">
            <span>全部刷新</span>
          </i>
        </div>
        <div @click="closeAll">
          <i class="el-icon-close">
            <span>关闭其他标签</span>
          </i>
        </div>
      </div>
      <div class="oa-router-tab">
        <el-tabs v-model="activeFrame"
                 @tab-click="openFromTab"
                 @tab-remove="removeTab">
          <el-tab-pane v-for="(item, index) in tabs"
                       :label="item.title"
                       :name="item.name"
                       style="height:0"
                       :key="index"
                       :closable="item.closable" />
        </el-tabs>
      </div>
    </div>
    <div class="container-box"
         v-auto-height
         v-loading="loading"
         element-loading-text="拼命加载中"
         element-loading-background="rgba(255, 255, 255, 1)">
      <keep-alive v-if="activeNow">
        <router-view></router-view>
      </keep-alive>
    </div>
    <keep-alive>
      <user-info v-if="userInfoVisible"
                 @close-window="closeUserInfoDialog" />
    </keep-alive>
  </div>
</template>

<script>
import { MkBase } from 'element-ui'
import { mapMutations, mapState } from 'vuex'
import UserInfo from '@/views/cp-user/user-info'

export default {
  mixins: [MkBase],
  name: 'desk',
  computed: {
    ...mapState(['menus', 'tabs', 'uris', 'title', 'loading', 'index'])
  },
  components: {
    UserInfo
  },
  data () {
    return {
      // 当前活动选项卡
      activeFrame: null,
      // 用户中心下拉菜单
      userCenter: false,
      // 客服中心下拉菜单
      kfCenter: false,
      // route-view开关，用于刷新页面
      activeNow: true,
      // 个人信息
      userInfoVisible: false,
      // socket客户端
      socket: null,
      // 消息下拉菜单
      msgDownList: false,
      // 消息数量
      messagenum: 10,
      // 消息
      messages: [
        {
          title: '【审核】 您有好多审核要处理,【审核】 您有好多审核要处理',
          msg:
            '【审核】 您有好多审核要处理【审核】 您有好多审核要处理【审核】 您有好多审核要处理',
          murl: '',
          mstate: true
        }
      ]
    }
  },
  watch: {
    /**
     * 监控路由变化，将变化全部写入到页面tabs中
     * */
    $route () {
      this.gotoActiveRoute(this.$route)
    }
  },
  methods: {
    ...mapMutations(['BIND_TABS', 'UNBIND_ALL', 'BIND_LOADING']),
    /**
     *  路由切换时，进行页面效果的调整
     */
    gotoActiveRoute (route, preIndex = false) {
      // 存在于路由映射表中,才进行 缓存以及选项卡展示
      const uri = this.uris.find(item => item.uri === route.path)
      if (uri) {
        this.tabs.forEach(tab => {
          tab.active = false
        })
        document.title = `${this.title} - ${uri.title}`
        const index = this.tabs.findIndex(frame => frame.name === route.name)
        if (index === -1) {
          const prePush = {
            name: route.name,
            path: route.path,
            title: uri.title,
            closable: route.path !== this.index,
            active: true
          }
          if (preIndex !== false) {
            this.tabs.splice(preIndex, 0, prePush)
          } else {
            this.tabs.push(prePush)
          }
        } else {
          this.tabs[index].active = true
        }
        this.activeFrame = route.name
        this.BIND_TABS(this.tabs)
      }
    },
    /**
     * 从顶部菜单打开页面
     * 此时打开新页面后，将当前router改装，并缓存到选项卡中
     * @param item
     */
    openFromMenu (item) {
      this.goto(item.view)
    },
    /**
     * 页面跳转
     */
    goto (path, force) {
      if ((path && this.$route.path !== path) || force === true) {
        this.BIND_LOADING(true)
        this.$router.replace(path)
      }
    },
    /**
     * 从选项卡中切换打开页面
     */
    openFromTab (thisTab) {
      const item = this.tabs.find(tab => tab.name === thisTab.name)
      this.goto(item.path)
    },
    /**
     * 利用路由对象(tabs中缓存的)直接打开
     * @param item
     */
    openFromRoute (item) {
      this.goto(item.path)
    },
    /**
     * 移除一个页面
     * @param tabName
     */
    removeTab (tabName) {
      const tabIndex = this.tabs.findIndex(item => item.name === tabName)
      const active = this.tabs[tabIndex].active
      this.tabs.splice(+tabIndex, 1)
      this.BIND_TABS(this.tabs)
      if (active === true) {
        this.openFromRoute(this.tabs[tabIndex - 1])
      }
    },
    /**
     * 关闭全部（其他）
     */
    closeAll () {
      const newList = []
      for (let [i, v] of this.tabs.entries()) {
        if (i === 0 || `${v.name}` === this.activeFrame) {
          newList.push(v)
        }
      }
      this.tabs.length = 0
      newList.forEach(item => this.tabs.push(item))
      this.BIND_TABS(this.tabs)
    },
    /**
     * 刷新选项卡,todo 黑科技
     */
    refresh () {
      const index = this.tabs.findIndex(item => item.active === true)
      this.tabs.splice(index, 1)
      this.activeNow = false
      this.$nextTick(() => {
        this.activeNow = true
        this.gotoActiveRoute(this.$route, index)
      })
    },
    /**
     * 打开个人信息编辑界面
     */
    editInfo () {
      this.userInfoVisible = true
    },
    /**
     * 关闭个人编辑界面
     */
    closeUserInfoDialog () {
      this.userInfoVisible = false
    },
    /**
     * 退出登录
     * @returns {Promise<void>}
     */
    async logout () {
      await this.$post('loginout.json')
      this.UNBIND_ALL()
      this.goto('/login')
    },
    /**
     * 链接socket
     * @returns {Promise<void>}
     */
    async connectSocket () {
      if (window.WebSocket) {
        this.socket = new WebSocket(
          `${this.wsPath}/ws/msg?userid=${this.user.userid}`
        )
        // 打开Socket
        // 发送一个初始化消息
        this.socket.onopen = () => {
          this.socket.send(
            JSON.stringify({
              title: '初始化',
              msg: '初始化',
              murl: '',
              mstate: 0
            })
          )
        }
        // 监听消息
        this.socket.onmessage = event => {
          this.messages.unshift(JSON.parse(event.data))
          this.messagenum++
          if (this.messages.length > 5) {
            this.messages.pop()
          }
        }
        // 错误重连
        this.socket.onerror = async () => {
          await this.connectSocket()
        }
      }
    },
    /**
     * 加载个人消息
     * @returns {Promise<void>}
     */
    async loadMyMsgs () {
      let data = await this.$get('/cpMsg/mymsgs.json')
      if (data) {
        this.messagenum = data.totalRow
        this.messages = data.list
      }
    },
    /**
     * 阅读某一条消息
     * @param obj
     * @returns {Promise<void>}
     */
    async jumptourl (obj) {
      let data = await this.$get('/cpMsg/read.json', { mid: obj.mid })
      if (data) {
        this.messagenum = data.totalRow
        this.messages = data.list
      }
      if (obj && obj.murl) {
        this.$router.push({
          path: obj.murl,
          query: { view: true, id: obj.mid }
        })
      }
    },
    /**
     * 打开消息列表
     * @returns {Promise<void>}
     */
    async viewAllMyMsg () {
      this.$router.push({ path: '/cpMsg/my-msg-list' })
    }
  },
  created () {
    this.gotoActiveRoute(this.$route)
  },
  async mounted () {
    // await this.connectSocket()
  }
}
</script>

<style scoped>
li {
  list-style: none;
}
blockquote,
body,
button,
dd,
dl,
dt,
fieldset,
form,
h1,
h2,
h3,
h4,
h5,
h6,
hr,
input,
legend,
li,
ol,
p,
pre,
td,
textarea,
th,
ul {
  margin: 0;
  padding: 0;
}

.oa-header {
  height: 50px;
  line-height: 50px;
  background: #00a3ef;
  color: #fff;
  z-index: 5000;
}

.image-logo {
  background: url(~assets/images/logo4.png) no-repeat 50%;
}

.oa-header-logo {
  width: 50px;
}

.oa-header-logo,
.oa-header-msg,
.oa-header-nav {
  float: left;
  height: 50px;
}

.oa-header-id {
  float: left;
  margin-right: 20px;
}

.oa-header-logo,
.oa-header-msg,
.oa-header-nav {
  float: left;
  height: 50px;
}

.clearfix:after {
  content: ".";
  display: block;
  height: 0;
  clear: both;
  visibility: hidden;
}
.oa-header-msg > ul > li:hover,
.oa-header-nav > ul > li:hover {
  background: #0094ef;
}
.oa-header-msg > ul > li,
.oa-header-nav > ul > li {
  float: left;
  padding: 0 10px;
  font-size: 14px;
  cursor: pointer;
  height: 50px;
  line-height: 50px;
  position: relative;
}

.oa-header-nav > ul > li i {
  padding-left: 5px;
  font-size: 11px;
}

.oa-header-nav-select {
  position: absolute;
  left: 0;
  top: 46px;
  padding: 10px;
  width: 555px;
  box-shadow: 0 0 15px rgba(0, 0, 0, 0.2);
  background: #fff;
  z-index: 9999;
}

.oa-header-nav-select h3 {
  height: 30px;
  line-height: 30px;
  font-size: 14px;
  font-weight: 700;
  color: #333;
  text-align: left;
}

.oa-header-nav-select li {
  margin-left: 25px;
  float: left;
  width: 20%;
  color: #666;
  height: 28px;
  line-height: 28px;
  font-size: 14px;
}

.oa-header-nav-select li:hover {
  color: #00a3ef;
}

.oa-header-msg {
  float: right;
}

.oa-header-call-box {
  position: absolute;
  width: 200px;
  padding: 10px;
  font-size: 14px;
  z-index: 99;
  right: 0;
  top: 46px;
  background: #fff;
  color: #666;
  box-shadow: 0 0 15px rgba(0, 0, 0, 0.2);
}

.oa-header-call-a,
.oa-header-call-b {
  line-height: 20px;
  padding: 10px 0;
}

.oa-header-call-a {
  text-align: center;
  border-bottom: 1px solid #e3e3e3;
}

.oa-header-call-c {
  line-height: 24px;
}

.oa-header-call-c a {
  display: block;
  padding: 0 10px;
  color: #fff;
  text-align: center;
  margin: 4px 0;
}

.oa-header-call-b h3,
.oa-header-call-b p {
  font-size: 14px;
}

.oa-header-msg li i {
  padding-right: 5px;
  font-size: 16px;
}

.oa-header-call-c-qq {
  background: #ff4949;
}

.oa-header-call-c-ww {
  background: #20a0ff;
}

.oa-header-call-c-help {
  background: #13ce66;
}

.oa-header-call-c-video {
  background: #f7ba2a;
}

.oa-header-user-box {
  position: absolute;
  width: 120px;
  font-size: 14px;
  z-index: 99;
  right: 0;
  top: 46px;
  background: #fff;
  color: #666;
  box-shadow: 0 0 15px rgba(0, 0, 0, 0.2);
}

.oa-header-user-box li {
  line-height: 40px;
  text-align: center;
}

.oa-header-msg li i {
  padding-right: 5px;
  font-size: 16px;
}

.oa-router {
  height: 40.4px;
  line-height: 30px;
  z-index: 55;
  position: relative;
  border-bottom: 1px solid #e4e5e7;
}

.oa-router-btn {
  position: absolute;
  right: 0;
  top: 0;
  z-index: 999;
}

.oa-router-btn div {
  float: left;
  cursor: pointer;
  text-align: center;
  border-left: 1px solid #d1dbe5;
  padding: 0 10px;
  color: #666;
  height: 40px;
  line-height: 42px;
}

.oa-router-btn i {
  height: 42px;
  line-height: 42px;
  font-size: 18px;
}

.oa-router-btn span {
  font-size: 12px;
  margin-left: 5px;
  line-height: 42px;
  height: 42px;
}

.oa-router-tab {
  width: calc(100% - 236px);
}

.oa-header-ms-box {
  position: absolute;
  width: 200px;
  font-size: 14px;
  z-index: 99;
  right: 0;
  top: 46px;
  background: #fff;
  color: #666;
  box-shadow: 0 0 15px rgba(0, 0, 0, 0.2);
}
.oa-header-ms-box li {
  line-height: 40px;
  text-align: center;
}
.ms-badge-item {
  vertical-align: baseline;
}
.container-box {
  width: 100%;
  height: 100%;
  overflow: hidden;
  padding: 3px 3px 0 3px;
  font-size: 13px;
  margin-top: -1px;
}
.el-badge >>> .el-badge__content.is-fixed {
  margin-top: 10px;
  margin-right: 40px;
  top: -17px;
  font-size: 7px;
  right: auto;
  left: -17px;
  padding: 0 2px;
  line-height: 15px;
  -moz-transform: rotate(-20deg);
  -webkit-transform: rotate(-20deg);
  -o-transform: rotate(-20deg);
  -ms-transform: rotate(-20deg);
  transform: rotate(-20deg);
}
.ms-badge-item >>> .el-badge__content.is-fixed {
  top: 0;
  font-size: 8px;
  right: -45px;
  left: auto;
}
</style>

